package service

import (
	"backend_api/internal/global"
	"backend_api/internal/model"
	"backend_api/internal/model/request"
	"backend_api/internal/utils"
	"errors"
)

type AdminUserService struct{}

func (s *AdminUserService) GetList(req *request.AdminUserListReq) (list []model.User, total int64, err error) {
	db := global.DB.Model(&model.User{})

	if req.Email != "" {
		db = db.Where("email LIKE ?", "%"+req.Email+"%")
	}
	if req.Phone != "" {
		db = db.Where("phone LIKE ?", "%"+req.Phone+"%")
	}
	if req.Status != nil {
		db = db.Where("status = ?", *req.Status)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10 // 设置默认每页显示10条
	}

	err = db.Limit(req.PageSize).Offset((req.Page - 1) * req.PageSize).
		Order("id DESC").
		Find(&list).Error

	return
}

func (s *AdminUserService) Update(req *request.AdminUserUpdateReq) error {
	var user model.User
	if err := global.DB.First(&user, req.ID).Error; err != nil {
		return errors.New("用户不存在")
	}

	// 检查邮箱是否已被其他用户使用
	if user.Email != req.Email {
		var count int64
		global.DB.Model(&model.User{}).Where("email = ? AND id != ?", req.Email, req.ID).Count(&count)
		if count > 0 {
			return errors.New("邮箱已被使用")
		}
	}

	// 检查手机号是否已被其他用户使用
	if user.Phone != req.Phone {
		var count int64
		global.DB.Model(&model.User{}).Where("phone = ? AND id != ?", req.Phone, req.ID).Count(&count)
		if count > 0 {
			return errors.New("手机号已被使用")
		}
	}

	return global.DB.Model(&user).Updates(map[string]interface{}{
		"email": req.Email,
		"phone": req.Phone,
	}).Error
}

func (s *AdminUserService) UpdateStatus(req *request.AdminUserStatusReq) error {
	// 先查询当前用户状态
	var user model.User
	if err := global.DB.First(&user, req.ID).Error; err != nil {
		return err
	}

	// 自动切换状态：如果当前是1就改为0，如果是0就改为1
	newStatus := 1
	if user.Status == 1 {
		newStatus = 0
	}
	// 更新用户状态
	err := global.DB.Model(&user).Update("status", newStatus).Error
	return err
}

func (s *AdminUserService) ResetPassword(req *request.AdminUserResetPwdReq) (string, error) {
	var user model.User
	if err := global.DB.First(&user, req.ID).Error; err != nil {
		return "", errors.New("用户不存在")
	}

	if err := global.DB.Model(&user).Update("password", utils.MD5("123456")).Error; err != nil {
		return "", err
	}

	return "", nil
}
